package util

import (
	"strconv"
	"time"

	"fmt"
	"os/exec"
	"errors"
	"flag"
	"io/ioutil"
	"sync"
	"github.com/garyburd/redigo/redis"

	"io"
	"bufio"
	"strings"
	"os"
)

var (
	serverPath     = flag.String("redis-server", "/usr/local/bin/redis-server", "Path to redis server binary")
	serverBasePort = flag.Int("redis-port", 6379, "Beginning of port range for test servers")
	serverLog      = ioutil.Discard

	defaultServerMu  sync.Mutex
	defaultServer    *Server
	defaultServerErr error
)

func DialDefaultServer() (redis.Conn, error) {
	if err := startDefaultServer(); err != nil {
		return nil, err
	}

	c, err := redis.Dial("tcp", fmt.Sprintf(":%d", *serverBasePort), redis.DialReadTimeout(1*time.Second), redis.DialWriteTimeout(1*time.Second))
	if err != nil {
		return nil, err
	}
	c.Do("FLUSHDB")
	return c, nil

}

var rsg redis.Conn = nil

func GetRedisConn(host string, db int) (redis.Conn) {

	if rsg != nil {
		return rsg
	}

	rs, err := redis.Dial("tcp", host)
	if err != nil {
		defer rs.Close()
		fmt.Println(err)
		fmt.Println("redis connect error")
		return nil
	}
	rs.Do("SELECT", db)
	rsg = rs
	return rsg
}

func startDefaultServer() error {
	defaultServerMu.Lock()
	defer defaultServerMu.Unlock()
	if defaultServer != nil || defaultServerErr != nil {
		return defaultServerErr
	}
	defaultServer, defaultServerErr = NewServer(
		"default",
		"--port",
		strconv.Itoa(*serverBasePort),
		"--save", "",
		"--appendonly", "no")
	return defaultServerErr
}

func NewServer(name string, args ...string) (*Server, error) {
	s := &Server{
		name: name,
		cmd:  exec.Command(*serverPath, args...),
		done: make(chan struct{}),
	}

	r, err := s.cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}

	err = s.cmd.Start()
	if err != nil {
		return nil, err
	}

	ready := make(chan error, 1)
	go s.watch(r, ready)

	select {
	case err = <-ready:
	case <-time.After(time.Second * 10):
		err = errors.New("timeout waiting for server to start")
	}

	if err != nil {
		s.Stop()
		return nil, err
	}

	return s, nil
}

type Server struct {
	name string
	cmd  *exec.Cmd
	done chan struct{}
}

func (s *Server) watch(r io.Reader, ready chan error) {
	fmt.Fprintf(serverLog, "%d START %s \n", s.cmd.Process.Pid, s.name)
	var listening bool
	var text string
	scn := bufio.NewScanner(r)
	for scn.Scan() {
		text = scn.Text()
		fmt.Fprintf(serverLog, "%s\n", text)
		if !listening {
			if strings.Contains(text, " * Ready to accept connections") ||
				strings.Contains(text, " * The server is now ready to accept connections on port") {
				listening = true
				ready <- nil
			}
		}
	}
	if !listening {
		ready <- fmt.Errorf("server exited: %s", text)
	}
	s.cmd.Wait()
	fmt.Fprintf(serverLog, "%d STOP %s \n", s.cmd.Process.Pid, s.name)
	close(s.done)
}

func (s *Server) Stop() {
	s.cmd.Process.Signal(os.Interrupt)
	<-s.done
}
